import expressGraphQL from 'express-graphql';
import schema from './schema';
import {databaseUrl} from "./config";
import cors from "cors";
import mongoose from "mongoose";
import {printSchema} from "graphql/utilities/schemaPrinter";
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser'
import login from "./login";

var express = require('express')
var compression = require('compression')
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxyServer({})
var app = express()
mongoose.Promise = global.Promise;
mongoose.connect(databaseUrl, { useMongoClient: true });
let db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function(callback) {
    // yay!
    console.log("open DB");
});
app.use('*', cors());
app.use(compression())
app.use(express.static(__dirname));
app.use(bodyParser.json({limit: "10000 kB"}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
proxy.on('error', function (err, req, res) {
  console.error(err.toString());
  res.writeHead(500, { 'Content-Type': 'text/plain' })
  res.end('Something went wrong. And we are reporting a custom error message.')
})

app.use(express.static('build'))

app.use("/schema", (req, res) => {
  res.set("Content-Type", "text/plain");
  res.send(printSchema(schema));
});
app.use("/login", function(req, res, next) {
  login(req, res, next);
});
app.use("/validateToken", function(req, res, next) {
  res.send({
      status: 1
  });
});

app.use(
  "/graphql",
  expressGraphQL(req => {
      return {
          schema,
          graphiql: true,
          rootValue: {request: req},
          pretty: true,
          formatError: error => {
              return {
                  message: error.message,
                  locations: error.locations,
                  path: error.path
              };
          }
      };
  })
);
export default app;

